package dbs

import (
	"github.com/jinzhu/gorm"
	"time"
)

type DbOperation struct {
	Id         uint      `json:"id" gorm:"primary_key"`
	ReviewBy   string    `json:"review_by"`   //审批人
	ReviewAt   time.Time `json:"review_at"`   //审批时间
	ReviewType string    `json:"review_type"` //审批类型
	ReviewId   uint      `json:"review_id"`   //审批id
	ObjectRole string    `json:"object_role"` //目标角色
	ObjectName string    `json:"object_name"` //目标名字
	Department string    `json:"department"`  //目标科室
	CreatedAt  time.Time `json:"created_at"`
	UpdateAt   time.Time `json:"update_at"`
}

type DbOperationCreate struct {
	ReviewBy   string    `json:"review_by"`
	ReviewAt   time.Time `json:"review_at"`
	ReviewType string    `json:"review_type"`
	ObjectRole string    `json:"object_role"`
	ObjectName string    `json:"object_name"`
}

type DbOperationList struct {
	ReviewBy   string    `json:"review_by"`
	ReviewAt   time.Time `json:"review_at"`
	ReviewType string    `json:"review_type"`
	ObjectRole string    `json:"object_role"`
	ObjectName string    `json:"object_name"`
	Department string    `json:"department"`
	Page       int       `json:"page" label:"页数"`
	Limit      int       `json:"limit" label:"每页显示数"`
	Order      string    `json:"order" `
}

func (self *DbOperation) Create() (err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		return conn.Create(&self).Error
	})
	return
}

func (self *DbOperation) Query(s_list DbOperationList) (result []DbOperation, err error) {
	err = D_Pool(func(db **gorm.DB) (err error) {
		conn := *db

		if s_list.Department != "" {
			conn = conn.Where("department = ?", s_list.Department)
		}

		// 分页
		if s_list.Page != 0 && s_list.Limit != 0 {
			conn = conn.Offset((s_list.Page - 1) * s_list.Limit).Limit(s_list.Limit)
		}

		if s_list.Order != "" {
			conn = conn.Order(s_list.Order)
		} else {
			conn = conn.Order("id DESC")
		}

		return conn.Find(&result).Error
	})
	return
}
